from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import images
from google.appengine.ext.webapp import template

import appengine_admin
import cgi
import re
import datetime
import errors
import binascii

from xml.etree.ElementTree import parse, fromstring, XML
from django.utils import simplejson as json 

from models import *

def intersect(a, b):
    if not(a):
        return b
    if not(b):
        return a
    else:
        return list(set(a) & set(b))

def optionalargsjson(obj,field,):
    try:
        return obj[field]
    except:
	return None

def datetimeIterator(from_date=None, to_date=None, delta=datetime.timedelta(days=1) ):
    from_date = from_date or datetime.date.today()
    while to_date is None or from_date <= to_date:
	yield from_date
	from_date = from_date + delta
    return

"""
/rest/(v1|v2)/event/id/(eventid#)

GET (xml, json)
given a eventid, it returns an event and its full information


JSON(v2)
if event
   -returns {'event': {'id':eid, 'attending':[...] ...} }
if no matching id for event
   -returns {'event':None}

category, location, attending is empty list if no corresponding data
  attending
   - if empty, {'event': {... 'attending': [] ...} }
   - if not empty, {'event': {... 'attending': [{'id':uid, 'date_updated': 2011-06-20},...] ...} }
  category
   - if empty, {'event': {... 'categories': [] ...} }
   - if not empty, {'event': {... 'categories': [{'maincategory': catid, 'subcategory': catid}, ...]  ...} }
  locations
   - if empty, {'event': {... 'locations': [] ...} }
   - if not empty, {'event': {... 'locations': [{'city':Orlando, 'state':FL, 'zip':20123, 'address':123 Main Street,...}, ...]  ...} }

"""


class EventInfo(webapp.RequestHandler):
    def options(self, version, ID):
        self.response.headers['Content-Type'] = "application/json"
        self.response.headers['Access-Control-Allow-Origin'] = "*"
        self.response.headers['Vary'] = "Origin"
        self.response.headers['Access-Control-Allow-Methods'] = "OPTIONS, GET, POST, PUT, DELETE"
        self.response.headers['Access-Control-Allow-Headers'] = "Content-Type"           
        return
        
    def get(self, version, ID):
        event= Gaevent.get_by_id(int(ID))
	if version == 'v1':
	    self.response.headers['Content-Type'] = "text/xml"
            self.response.out.write(
"""<?xml version="1.0" encoding='utf-8'?>
<event>"""
	    )
            self.response.out.write(
"""    
	<id>%s</id>
	<name>%s</name>
	<description>%s</description>
	<tickets>%s</tickets>
	<supportemail>%s</supportemail>
	<supportphone>%s</supportphone>
	<event_start_date>%s</event_start_date>
	<event_end_date>%s</event_end_date>
	<event_start_time>%s</event_start_time>
	<event_end_time>%s</event_end_time>
	<event_expiration>%s</event_expiration>
	<is_featured>%s</is_featured>
	<price>%s</price>
	<likecount>%s</likecount>
	<date_created>%s</date_created>
	<status>%s</status>
        <business>%s</business>
	<date_updated>%s</date_updated>""" % (event.key().id(), event.eventname,  event.eventdescription , event.tickets, event.supportemail, event.supportphone, event.eventstartdate, event.eventenddate, event.eventstarttime, event.eventendtime, event.eventexpiration, event.is_featured, event.price, event.likecount, event.date_created, event.is_active, event.gabusiness.key().id(), event.date_updated )
	    )

	    self.response.out.write(
"""
	<categories>
	    <category>"""
	    )
	    if event.gacategory.categoryparentname:
		self.response.out.write(
"""
		<maincategory>%s</maincategory>
	        <subcategory>%s</subcategory>""" % (event.gacategory.categoryparentname.key().id() , event.gacategory.key().id() )
		)
	    else:
		self.response.out.write(
"""
	        <maincategory>%s</maincategory>""" %  event.gacategory.key().id()
		)
	    self.response.out.write(
"""
	    </category>"""
	    )

	    if (event.event_categories).count():
	        for eventcategory in event.event_categories:
		    self.response.out.write(
"""
	    <category>"""
		    )
		    if eventcategory.gacategory.categoryparentname:
	                self.response.out.write(
"""
		<maincategory>%s</maincategory>
	        <subcategory>%s</subcategory>""" % (eventcategory.gacategory.categoryparentname.key().id() , eventcategory.gacategory.key().id() )
		        )
		    else:
		        self.response.out.write(
"""
	        <maincategory>%s</maincategory>""" %  eventcategory.gacategory.key().id()
		        )
		    self.response.out.write(
"""
	    </category>"""
		    )
	    self.response.out.write(
"""
	</categories>"""
		)
	    eventimages = event.event_images.get()
	    if eventimages != None:
	        mainimage = eventimages.mainimage
		self.response.out.write(
"""
	<images>"""
		)
		if eventimages.image1:
                    self.response.out.write(
"""
	    <image main='%s'><img src='/rest/v1/event/img?img_number=1&amp;img_id=%s'></img></image>""" % (mainimage == 1, eventimages.key() )
	      	    )
		if eventimages.image2:
                    self.response.out.write(
"""
	    <image main='%s'><img src='/rest/v1/event/img?img_number=2&amp;img_id=%s'></img></image>""" % (mainimage == 2, eventimages.key() )
	      	    )
		if eventimages.image3:
                    self.response.out.write(
"""
	    <image main='%s'><img src='/rest/v1/event/img?img_number=3&amp;img_id=%s'></img></image>""" % (mainimage == 3, eventimages.key() )
	      	    )
		if eventimages.image4:
                    self.response.out.write(
"""
	    <image main='%s'><img src='/rest/v1/event/img?img_number=4&amp;img_id=%s'></img></image>""" % (mainimage == 4, eventimages.key() )
	      	    )
		self.response.out.write(
"""
	</images>"""
		)
	#each event has one location? no need to do a multiple location check?
	#event location needs a date udpated?
	    if (event.event_locations).count():
                self.response.out.write(
"""
        <location>"""
		)
                for eventlocation in event.event_locations:
	            self.response.out.write(
"""            
	    <id>%d</id>
	    <geocode>%s</geocode>
            <address>%s</address>
            <city>%s</city>
            <state>%s</state>
            <zip>%s</zip>""" % (eventlocation.key().id(), eventlocation.geopoint, eventlocation.address, eventlocation.city, eventlocation.state, eventlocation.zipcode)
		    )
	        self.response.out.write(
"""
	</location>"""
	        )

	    if (event.events_users).count():
                self.response.out.write("""
        <attending>"""
                )
                for eachuser in event.events_users:
	            self.response.out.write(
"""  
            <user>
	        <id>%s</id>
		<username>%s</username>
		<email>%s</email>
		<firstname>%s</firstname>
		<lastname>%s</lastname>
		<is_active>%s</is_active>
		<is_public>%s</is_public>
		<date_updated>%s</date_updated>
	    </user>"""  % (eachuser.gauser.key().id(),eachuser.gauser.username, eachuser.gauser.email, eachuser.gauser.firstname, eachuser.gauser.lastname, eachuser.gauser.is_active, eachuser.gauser.is_public, eachuser.gauser.date_updated) 
	            )
	        self.response.out.write(
"""
        </attending>"""
	        )

            self.response.out.write(
"""
</event>"""
	    )
	    return
	elif version == 'v2':
 	    self.response.headers['Content-Type'] = "application/json"
 	    self.response.headers['Access-Control-Allow-Origin'] = "*"
 	    self.response.headers['Vary'] = "Origin"
 	    self.response.headers['Access-Control-Allow-Methods'] = "OPTIONS, GET, POST, PUT, DELETE"
 	    self.response.headers['Access-Control-Allow-Headers'] = "Content-Type"
         
	    eventaccount = {}
            if event != None:
		tempevent = {
			     'id': event.key().id(),   
			     'name': event.eventname,
			     'description': event.eventdescription ,
			     'tickets': event.tickets,
			     'supportemail': event.supportemail,
			     'supportphone': event.supportphone,
			     'event_start_date': str(event.eventstartdate),
			     'event_end_date': str(event.eventenddate),
			     'event_start_time': str(event.eventstarttime),
			     'event_end_time': str(event.eventendtime),
			     'event_expiration': str(event.eventexpiration),
			     'is_featured': event.is_featured,
			     'price': event.price,
			     'likecount': event.likecount,
			     'date_created': str(event.date_created),
			     'status': event.is_active,
			     'business': event.gabusiness.key().id(),
			     'date_updated': str(event.date_updated),
			    }
		#changed this fro json not xml, bizliteinfo is returned with event
	        tempbiz =	{
			'id': event.gabusiness.key().id(),
			'bizname': event.gabusiness.bizname ,
			'is_active': event.gabusiness.is_active,
			'date_updated': str(event.gabusiness.date_updated),
			}

	        if (event.gabusiness.business_locations).count():
		    tempbiz['location'] = []
                    for bizlocation in event.gabusiness.business_locations:
		        temploc =	{
				'geocode': str(bizlocation.geopoint),
				'address': bizlocation.address,
				'city': bizlocation.city,
				'state': bizlocation.state,
				'zip': bizlocation.zipcode,
				'country': bizlocation.country,
				}
		        tempbiz['location'].append( temploc)
	        tempevent['business'] = tempbiz


		tempevent['categories'] = []
		tempcategory = {}
		if event.gacategory.categoryparentname:
		    tempcategory['maincategory'] = event.gacategory.categoryparentname.key().id()
		    tempcategory['subcategory'] = event.gacategory.key().id()
		else:
		    tempcategory['maincategory'] = event.gacategory.key().id()
		tempevent['categories'].append(tempcategory)

	        if (event.event_categories).count():
	            for eventcategory in event.event_categories:
		        tempcategory = {}

		        if eventcategory.gacategory.categoryparentname:
			    tempcategory['maincategory'] = eventcategory.gacategory.categoryparentname.key().id()
			    tempcategory['subcategory'] = eventcategory.gacategory.key().id()
		        else:
			    tempcategory['maincategory'] = eventcategory.gacategory.key().id()
		        tempevent['categories'].append(tempcategory)
		eventimages = event.event_images.get()
	        if eventimages != None:
		    mainimage = eventimages.mainimage
		    tempevent['images'] = []
		    if eventimages.image1:
			tempimage = 	{
					'main':mainimage == 1 ,
					'imagesrc':"src='/rest/v2/event/img?img_number=1&amp;img_id=%s'" % eventimages.key()	
					}
                        tempevent['images'].append(tempimage)
		    if eventimages.image2:
			tempimage = 	{
					'main':mainimage == 2,
					'imagesrc':"src='/rest/v2/event/img?img_number=2&amp;img_id=%s'" % eventimages.key()	
					}
                        tempevent['images'].append(tempimage)
		    if eventimages.image3:
			tempimage = 	{
					'main':mainimage == 3,
					'imagesrc':"src='/rest/v2/event/img?img_number=3&amp;img_id=%s'" % eventimages.key()	
					}
                        tempevent['images'].append(tempimage)
		    if eventimages.image4:
			tempimage = 	{
					'main':mainimage == 4,
					'imagesrc':"src='/rest/v2/event/img?img_number=4&amp;img_id=%s'" % eventimages.key()	
					}
                        tempevent['images'].append(tempimage)

		tempevent['locations'] = []
	        if (event.event_locations).count():
                    for eventlocation in event.event_locations:
		        temploc = 	{
					'id': eventlocation.key().id(),
					'geocode': str(eventlocation.geopoint),
					'address': eventlocation.address,
					'city': eventlocation.city,
					'state': eventlocation.state,
					'zip': eventlocation.zipcode,
					}
		        tempevent['locations'].append(temploc)

		tempevent['attending'] = []
	        if (event.events_users).count():   
                    for eachuser in event.events_users:

	                tempuser = 	{
			"id": eachuser.gauser.key().id(),
			"username": eachuser.gauser.username,
			"email": eachuser.gauser.email,
			"firstname": eachuser.gauser.firstname,
			"lastname": eachuser.gauser.lastname,
			"is_active": eachuser.gauser.is_active,
			"is_public": eachuser.gauser.is_public,
			"date_updated": str(eachuser.gauser.date_updated),
			   	}
		        tempevent['attending'].append(tempuser)	
	        eventaccount['event'] = tempevent			
                self.response.out.write( json.dumps(eventaccount) )
	        return
            else:
		self.response.out.write( json.dumps({'event':None}))
		return
	else:
	    # will have to enter v1 or v2. nothing else should go through
	    return

"""
/rest/(v1|v2)/event/lite/id/(eventid#)

GET (xml, json)
given a eventid, it returns an event and its lite information


JSON(v2)
if event
   -returns {'event': {'id':eid, 'attending':[...] ...} }
if no matching id for event
   -returns {'event':None}

category, location, attending is empty list if no corresponding data
  attending
   - if empty, {'event': {... 'attending': [] ...} }
   - if not empty, {'event': {... 'attending': [{'id':uid, 'date_updated': 2011-06-20},...] ...} }
  category
   - if empty, {'event': {... 'categories': [] ...} }
   - if not empty, {'event': {... 'categories': [{'maincategory': catid, 'subcategory': catid}, ...]  ...} }
  locations
   - if empty, {'event': {... 'locations': [] ...} }
   - if not empty, {'event': {... 'locations': [{'city':Orlando, 'state':FL, 'zip':20123, 'address':123 Main Street,...}, ...]  ...} }

"""

class EventLiteInfo(webapp.RequestHandler):
    def options(self, version, ID):
        self.response.headers['Content-Type'] = "application/json"
        self.response.headers['Access-Control-Allow-Origin'] = "*"
        self.response.headers['Vary'] = "Origin"
        self.response.headers['Access-Control-Allow-Methods'] = "OPTIONS, GET, POST, PUT, DELETE"
        self.response.headers['Access-Control-Allow-Headers'] = "Content-Type"           
        return    
    def get(self, version, ID):
        event= Gaevent.get_by_id(int(ID))
	if version == 'v1':
	    self.response.headers['Content-Type'] = "text/xml"
            self.response.out.write(
"""<?xml version="1.0" encoding='utf-8'?>
<event>"""
	    )
            self.response.out.write(
"""    
	<id>%s</id>
	<name>%s</name>
	<event_start_date>%s</event_start_date>
	<event_start_time>%s</event_start_time>
	<event_expiration>%s</event_expiration>
	<is_featured>%s</is_featured>
	<price>%s</price>
	<likecount>%s</likecount>
	<status>%s</status>
	<business>%s</business>
	<date_updated>%s</date_updated>""" % (event.key().id(), event.eventname, event.eventstartdate,  event.eventstarttime, event.eventexpiration, event.is_featured, event.price, event.likecount, event.is_active, event.gabusiness.key().id(), event.date_updated)
	    )
	    self.response.out.write(
"""
	<categories>
	    <category>"""
	    )
	    if event.gacategory.categoryparentname:
		self.response.out.write(
"""
		<maincategory>%s</maincategory>
	        <subcategory>%s</subcategory>""" % (event.gacategory.categoryparentname.key().id() , event.gacategory.key().id() )
		)
	    else:
		self.response.out.write(
"""
	        <maincategory>%s</maincategory>""" %  event.gacategory.key().id()
		)
	    self.response.out.write(
"""
	    </category>"""
	    )
	    if (event.event_categories).count():
	        
	        for eventcategory in event.event_categories:
		    self.response.out.write(
"""
	    <category>"""
		    )
		    if eventcategory.gacategory.categoryparentname:
	                self.response.out.write(
"""
		<maincategory>%s</maincategory>
	        <subcategory>%s</subcategory>""" % (eventcategory.gacategory.categoryparentname.key().id() , eventcategory.gacategory.key().id() )
		        )
		    else:
		        self.response.out.write(
"""
	        <maincategory>%s</maincategory>""" %  eventcategory.gacategory.key().id()
		        )
		    self.response.out.write(
"""
	    </category>"""
		    )
	    self.response.out.write(
"""
	</categories>"""
	    )
	    eventimages = event.event_images.get()
	    if eventimages != None:
		mainimage = eventimages.mainimage
		self.response.out.write(
"""
	<images>"""
		)
		if eventimages.mainimage == 1:
                    self.response.out.write(
"""
	    <image main='%s'><img src='/rest/v1/event/img?img_number=1&amp;img_id=%s'></img></image>""" % (mainimage == 1, eventimages.key() )
	      	    )
		elif eventimages.mainimage == 2:
                    self.response.out.write(
"""
	    <image main='%s'><img src='/rest/v1/event/img?img_number=2&amp;img_id=%s'></img></image>""" % (mainimage == 2, eventimages.key() )
	      	    )
		elif eventimages.mainimage == 3:
                    self.response.out.write(
"""
	    <image main='%s'><img src='/rest/v1/event/img?img_number=3&amp;img_id=%s'></img></image>""" % (mainimage == 3, eventimages.key() )
	      	    )
		elif eventimages.mainimage == 4:
                    self.response.out.write(
"""
	    <image main='%s'><img src='/rest/v1/event/img?img_number=4&amp;img_id=%s'></img></image>""" % (mainimage == 4, eventimages.key() )
	      	    )
		else:
		    self.response.out.write(
"""
	    <image main='%s'><img src='/rest/v1/event/img?img_number=1&amp;img_id=%s'></img></image>""" % (mainimage == 1, eventimages.key() )
	      	    )		
		self.response.out.write(
"""
	</images>"""
		)
	    if (event.events_users).count():
                self.response.out.write(
"""
        <attending>"""
                )
                for eachuser in event.events_users:
	            self.response.out.write(
"""  
            <user><id>%s</id></user>"""  % eachuser.gauser.key().id() 
	            )
	        self.response.out.write(
"""
        </attending>"""
	        )

            self.response.out.write(
"""
</event>"""
	    )

	elif version == 'v2':
 	    self.response.headers['Content-Type'] = "application/json"
 	    self.response.headers['Access-Control-Allow-Origin'] = "*"
 	    self.response.headers['Vary'] = "Origin"
 	    self.response.headers['Access-Control-Allow-Methods'] = "OPTIONS, GET, POST, PUT, DELETE"
 	    self.response.headers['Access-Control-Allow-Headers'] = "Content-Type"
 	    eventaccount = {}
            if event != None:

		tempevent = {
			     'id': event.key().id(),   
			     'name': event.eventname,
			     'event_start_date': str(event.eventstartdate),
			     'event_start_time': str(event.eventstarttime),
			     'event_expiration': str(event.eventexpiration),
			     'is_featured': event.is_featured,
			     'price': event.price,
			     'likecount': event.likecount,
			     'date_created': str(event.date_created),
			     'status': event.is_active,
			     'business': event.gabusiness.key().id(),
			     'date_updated': str(event.date_updated),
			    }

		tempevent['categories'] = []
		tempcategory = {}
		if event.gacategory.categoryparentname:
		    tempcategory['maincategory'] = event.gacategory.categoryparentname.key().id()
		    tempcategory['subcategory'] = event.gacategory.key().id()
		else:
		    tempcategory['maincategory'] = event.gacategory.key().id()
		tempevent['categories'].append(tempcategory)

	        if (event.event_categories).count():
	            for eventcategory in event.event_categories:
		        tempcategory = {}

		        if eventcategory.gacategory.categoryparentname:
			    tempcategory['maincategory'] = eventcategory.gacategory.categoryparentname.key().id()
			    tempcategory['subcategory'] = eventcategory.gacategory.key().id()
		        else:
			    tempcategory['maincategory'] = eventcategory.gacategory.key().id()
		        tempevent['categories'].append(tempcategory)

	        eventimages = event.event_images.get()
	        if eventimages != None:
		    mainimage = eventimages.mainimage
		    tempevent['images'] = []
		    if eventimages.mainimage == 1:
			tempimage =	{
					'mainimage': mainimage == 1,								
					'imagesrc': "src='/rest/v2/event/img?img_number=1&amp;img_id=%s'" % eventimages.key()
					}
                        tempevent['images'].append(tempimage)
		    elif eventimages.mainimage == 2:
			tempimage =	{
					'mainimage': mainimage == 2,								
					'imagesrc': "src='/rest/v2/event/img?img_number=2&amp;img_id=%s'" % eventimages.key()
					}
                        tempevent['images'].append(tempimage)
		    elif eventimages.mainimage == 3:
			tempimage =	{
					'mainimage': mainimage == 3,								
					'imagesrc': "src='/rest/v2/event/img?img_number=3&amp;img_id=%s'" % eventimages.key()
					}
                        tempevent['images'].append(tempimage)
		    elif eventimages.mainimage == 4:
			tempimage =	{
					'mainimage': mainimage == 4,								
					'imagesrc': "src='/rest/v2/event/img?img_number=4&amp;img_id=%s'" % eventimages.key()
					}
                        tempevent['images'].append(tempimage)
		    else :
			tempimage =	{
					'mainimage': mainimage == 1,								
					'imagesrc': "src='/rest/v2/event/img?img_number=1&amp;img_id=%s'" % eventimages.key()
					}
                        tempevent['images'].append(tempimage)


		tempevent['attending'] = []
	        if (event.events_users).count():
                    for eachuser in event.events_users:
		        tempuser =	{
					'id': eachuser.gauser.key().id(),
					}
		        tempevent['attending'].append(tempuser)	
	        eventaccount['event'] = tempevent			
                self.response.out.write( json.dumps(eventaccount) )
	        return
	    else:
		#return blank dictionary or event as null/None
		self.response.out.write( json.dumps({'event': None} ) )
		#self.response.out.write( json.dumps(eventaccount) )
		return

	else:
	    # will have to enter v1 or v2. nothing else should go through
	    return


"""
/rest/(v1|v2)/event/list

GET
returns all the given events and its lite info

notes:	mostly for debugging purposes

"""

class EventLiteList(webapp.RequestHandler):
    def options(self, version):
        self.response.headers['Content-Type'] = "application/json"
        self.response.headers['Access-Control-Allow-Origin'] = "*"
        self.response.headers['Vary'] = "Origin"
        self.response.headers['Access-Control-Allow-Methods'] = "OPTIONS, GET, POST, PUT, DELETE"
        self.response.headers['Access-Control-Allow-Headers'] = "Content-Type"           
        return

    def get(self, version):
        events= Gaevent.all()
	if version == 'v1':
            self.response.headers['Content-Type'] = "text/xml"
            self.response.out.write(
"""<?xml version="1.0" encoding='utf-8'?>
<events>"""
	    )
            for event in events:
                self.response.out.write(
"""
    <event>    
	    <id>%s</id>
	    <name>%s</name>
	    <event_start_date>%s</event_start_date>
	    <event_start_time>%s</event_start_time>
	    <event_expiration>%s</event_expiration>
	    <is_featured>%s</is_featured>
	    <price>%s</price>
	    <likecount>%s</likecount>
	    <status>%s</status>
            <business>%s</business>
	    <date_updated>%s</date_updated>""" % (event.key().id(), event.eventname, event.eventstartdate,  event.eventstarttime, event.eventexpiration, event.is_featured, event.price, event.likecount, event.is_active, event.gabusiness.key().id(), event.date_updated)
	        )
		self.response.out.write(
"""
	    <categories>
	        <category>"""
	        )
	        if event.gacategory.categoryparentname:
		    self.response.out.write(
"""
		    <maincategory>%s</maincategory>
	            <subcategory>%s</subcategory>""" % (event.gacategory.categoryparentname.key().id() , event.gacategory.key().id() )
		    )
		else:
		    self.response.out.write(
"""
	            <maincategory>%s</maincategory>""" %  event.gacategory.key().id()
		    )
	        self.response.out.write(
"""
	        </category>"""
	        )
	        if (event.event_categories).count():
	            
	            for eventcategory in event.event_categories:
		        self.response.out.write(
"""
	        <category>""")
		        if eventcategory.gacategory.categoryparentname:
	                    self.response.out.write(
"""
		    <maincategory>%s</maincategory>
	            <subcategory>%s</subcategory>""" % (eventcategory.gacategory.categoryparentname.key().id() , eventcategory.gacategory.key().id() )
		            )
		        else:
		            self.response.out.write(
"""
	            <maincategory>%s</maincategory>""" %  eventcategory.gacategory.key().id()
		            )
		        self.response.out.write(
"""
	        </category>""")
		self.response.out.write(
"""
	    </categories>""")
	        eventimages = event.event_images.get()
	        if eventimages != None:
		    mainimage = eventimages.mainimage
		    self.response.out.write(
"""
	<images>"""
		    )
		    if eventimages.mainimage == 1:
                        self.response.out.write(
"""
	    <image main='%s'><img src='/rest/v1/event/img?img_number=1&amp;img_id=%s'></img></image>""" % (mainimage == 1, eventimages.key() )
	      	        )
		    elif eventimages.mainimage == 2:
                        self.response.out.write(
"""
	    <image main='%s'><img src='/rest/v1/event/img?img_number=2&amp;img_id=%s'></img></image>""" % (mainimage == 2, eventimages.key() )
	      	        )
		    elif eventimages.mainimage == 3:
                        self.response.out.write(
"""
	    <image main='%s'><img src='/rest/v1/event/img?img_number=3&amp;img_id=%s'></img></image>""" % (mainimage == 3, eventimages.key() )
	      	        )
		    elif eventimages.mainimage == 4:
                        self.response.out.write(
"""
	    <image main='%s'><img src='/rest/v1/event/img?img_number=4&amp;img_id=%s'></img></image>""" % (mainimage == 4, eventimages.key() )
	      	        )
		    else:
		        self.response.out.write(
"""
	    <image main='%s'><img src='/rest/v1/event/img?img_number=1&amp;img_id=%s'></img></image>""" % (mainimage == 1, eventimages.key() )
	      	        )		
		    self.response.out.write(
"""
	</images>"""
		    )
		if (event.event_locations).count():
                    self.response.out.write(
"""
            <locations>"""
                    )
		    for eventlocation in event.event_locations:
                        self.response.out.write(
"""  
                <location><id>%s</id></location>"""  % eventlocation.key().id() 
	                )
                    self.response.out.write(
"""
            </locations>"""
	            )	
                if (event.events_users).count():
                    self.response.out.write(
"""
            <attending>"""
                    )
                    for eachuser in event.events_users:
                        self.response.out.write(
"""  
                <user><id>%s</id></user>"""  % eachuser.gauser.key().id() 
	                )
                    self.response.out.write(
"""
            </attending>"""
	            )

                self.response.out.write(
"""
    </event>"""
	        )
            self.response.out.write(
"""
</events>"""
            )

	elif version == 'v2':
 	    self.response.headers['Content-Type'] = "application/json"
 	    self.response.headers['Access-Control-Allow-Origin'] = "*"
 	    self.response.headers['Vary'] = "Origin"
 	    self.response.headers['Access-Control-Allow-Methods'] = "OPTIONS, GET, POST, PUT, DELETE"
 	    self.response.headers['Access-Control-Allow-Headers'] = "Content-Type"
     	    eventsaccount = {}
	    eventsaccount['events']= []
            for event in events:
		tempevent = {
			     'id': event.key().id(),   
			     'name': event.eventname,
			     'event_start_date': str(event.eventstartdate),
			     'event_start_time': str(event.eventstarttime),
			     'event_expiration': str(event.eventexpiration),
			     'is_featured': event.is_featured,
			     'price': event.price,
			     'likecount': event.likecount,
			     'status': event.is_active,
			     'business': event.gabusiness.key().id(),
			     'date_updated': str(event.date_updated),
			    }

		tempevent['categories'] = []
		tempcategory = {}
		if event.gacategory.categoryparentname:
		    tempcategory['maincategory'] = event.gacategory.categoryparentname.key().id()
		    tempcategory['subcategory'] = event.gacategory.key().id()
		else:
		    tempcategory['maincategory'] = event.gacategory.key().id()
		tempevent['categories'].append(tempcategory)
	        if (event.event_categories).count():   
	            for eventcategory in event.event_categories:
		        tempcategory = {}

		        if eventcategory.gacategory.categoryparentname:
			    tempcategory['maincategory'] = eventcategory.gacategory.categoryparentname.key().id()
			    tempcategory['subcategory'] = eventcategory.gacategory.key().id()
		        else:
			    tempcategory['maincategory'] = eventcategory.gacategory.key().id()
		        tempevent['categories'].append(tempcategory)
		tempevent['locations'] = []
		if (event.event_locations).count():
		    for eventlocation in event.event_locations:
			templocation = { 
					'id': eventlocation.key().id()
				    }
		    	tempevent['locations'].append(templocation)
	        eventimages = event.event_images.get()
	        if eventimages != None:
		    mainimage = eventimages.mainimage
		    tempevent['images'] = []
		    if eventimages.mainimage == 1:
			tempimage =	{
					'mainimage': mainimage == 1,								
					'imagesrc': "src='/rest/v2/event/img?img_number=1&amp;img_id=%s'" % eventimages.key()
					}
                        tempevent['images'].append(tempimage)
		    elif eventimages.mainimage == 2:
			tempimage =	{
					'mainimage': mainimage == 2,								
					'imagesrc': "src='/rest/v2/event/img?img_number=2&amp;img_id=%s'" % eventimages.key()
					}
                        tempevent['images'].append(tempimage)
		    elif eventimages.mainimage == 3:
			tempimage =	{
					'mainimage': mainimage == 3,								
					'imagesrc': "src='/rest/v2/event/img?img_number=3&amp;img_id=%s'" % eventimages.key()
					}
                        tempevent['images'].append(tempimage)
		    elif eventimages.mainimage == 4:
			tempimage =	{
					'mainimage': mainimage == 4,								
					'imagesrc': "src='/rest/v2/event/img?img_number=4&amp;img_id=%s'" % eventimages.key()
					}
                        tempevent['images'].append(tempimage)
		    else :
			tempimage =	{
					'mainimage': mainimage == 1,								
					'imagesrc': "src='/rest/v2/event/img?img_number=1&amp;img_id=%s'" % eventimages.key()
					}
                        tempevent['images'].append(tempimage)		
		tempevent['attending'] = []
	        if (event.events_users).count():  
                    for eachuser in event.events_users:
		        tempuser =	{
					'id': eachuser.gauser.key().id(),
					}
		        tempevent['attending'].append(tempuser)	

	        eventsaccount['events'].append(tempevent)
			
            self.response.out.write( json.dumps(eventsaccount) )
	    return

	else:
	    # will have to enter v1 or v2. nothing else should go through
	    return

"""
Get Events Amounts For Date Range
/rest/v2/event/count?daterange=YYYYMMDDYYYYMMDD
"""
class EventAmount(webapp.RequestHandler):
    def options(self, version):
        self.response.headers['Content-Type'] = "application/json"
        self.response.headers['Access-Control-Allow-Origin'] = "*"
        self.response.headers['Vary'] = "Origin"
        self.response.headers['Access-Control-Allow-Methods'] = "OPTIONS, GET, POST, PUT, DELETE"
        self.response.headers['Access-Control-Allow-Headers'] = "Content-Type"           
        return 

    def get(self, version):
	daterange = self.request.get(u'daterange') #YYYYMMDDYYYYMMDD
	fromdate = datetime.date(int(daterange[0:4]), int(daterange[4:6]), int(daterange[6:8]))
	todate = datetime.date(int(daterange[8:12]), int(daterange[12:14]), int(daterange[14:16]))

	if version == 'v2':
 	    self.response.headers['Content-Type'] = "application/json"
 	    self.response.headers['Access-Control-Allow-Origin'] = "*"
 	    self.response.headers['Vary'] = "Origin"
 	    self.response.headers['Access-Control-Allow-Methods'] = "OPTIONS, GET, POST, PUT, DELETE"
 	    self.response.headers['Access-Control-Allow-Headers'] = "Content-Type"
 	    eventaccount = {}
     	    eventaccount['eventsaccount'] = {}
	    for eachdate in datetimeIterator(fromdate, todate):
		result = db.GqlQuery( "SELECT __key__ from Gaevent WHERE eventstartdate = :1" , eachdate)
		eventaccount['eventsaccount'][str(eachdate)] = result.count()

	    self.response.out.write( json.dumps(eventaccount) )
	    return
	


"""
/rest/(v1|v2)/event/filter?category=(catid)&zipcode=(zip#)&startdate=(date)

URL Query Parameters
category (category id #), zipcode (standard US zipcode), startdate (MMDDYYYY) #maybe change to (YYYYMMDD)

GET (xml, json)
goes through each parameter and finds all events that match all query params. if param is not given, does not query it

JSON (v2)
returns a list of events if events are found
   -returns {'events': [ {event1}, {event2}... ] } 
if no events match
   -returns {'events': [] }

"""

class EventFilter(webapp.RequestHandler):
    def options(self, version):
        self.response.headers['Content-Type'] = "application/json"
        self.response.headers['Access-Control-Allow-Origin'] = "*"
        self.response.headers['Vary'] = "Origin"
        self.response.headers['Access-Control-Allow-Methods'] = "OPTIONS, GET, POST, PUT, DELETE"
        self.response.headers['Access-Control-Allow-Headers'] = "Content-Type"           
        return    
    def get(self, version):
	if version == 'v1':
	    self.response.headers['Content-Type'] = "text/xml"
            self.response.out.write(
"""<?xml version="1.0" encoding='utf-8'?>
<events>"""
	    )
	    events = None

	    startdate = self.request.get(u'startdate')
	    if startdate:
	        events = db.GqlQuery(	"SELECT * from Gaevent "+
                                    		"WHERE eventstartdate = :1 " +
						"ORDER BY eventstartdatetime",
                                      		datetime.date(int(startdate[0:4]), int(startdate[4:6]), int(startdate[6:8]) )
	        )
	    daterange = self.request.get(u'daterange') #YYYYMMDDYYYYMMDD
	    if daterange:
	        events = db.GqlQuery(	"SELECT * from Gaevent "+
                                    		"WHERE eventstartdate >= :1 AND eventstartdate <= :2 "+
						"ORDER BY eventstartdate, eventstartdatetime",
                                      		datetime.date(int(daterange[0:4]), int(daterange[4:6]), int(daterange[6:8])),
						datetime.date(int(daterange[8:12]), int(daterange[12:14]), int(daterange[14:16])),
	        )

	    categoryrequest = self.request.get(u'category')
	    if categoryrequest:
	        events = db.GqlQuery(	"SELECT * from Gaevent "+
					"WHERE eventcategories = :1 "+
					"ORDER BY eventstartdatetime",
					int(categoryrequest)
	        )
	    distancerequest = self.request.get(u'distance')
	    if distancerequest: 	
                self.response.out.write(
"""
does not support distance yet
</events>"""
	        )
	        return

	    if events == None:
	        events = Gaevent.all()

	    for event in events:
                self.response.out.write(
"""
        <event>"""
                )
                self.response.out.write(
"""    
	    <id>%s</id>
	    <name>%s</name>	 
	    <event_start_date>%s</event_start_date>
	    <event_start_time>%s</event_start_time>
	    <event_expiration>%s</event_expiration>
	    <is_featured>%s</is_featured>
	    <price>%s</price>
	    <likecount>%s</likecount>
	    <status>%s</status>
	    <business>%s</business>
	    <date_updated>%s</date_updated>""" % (event.key().id(), event.eventname,  event.eventstartdate, event.eventstarttime,  event.eventexpiration, event.is_featured, event.price, event.likecount, event.is_active, event.gabusiness.key().id(), event.date_updated )
	        )
		self.response.out.write(
"""
	    <categories>
	        <category>"""
	        )
	        if event.gacategory.categoryparentname:
		    self.response.out.write(
"""
		    <maincategory>%s</maincategory>
	            <subcategory>%s</subcategory>""" % (event.gacategory.categoryparentname.key().id() , event.gacategory.key().id() )
		    )
		else:
		    self.response.out.write(
"""
	            <maincategory>%s</maincategory>""" %  event.gacategory.key().id()
		    )
	        self.response.out.write(
"""
	        </category>"""
	        )
	        if (event.event_categories).count():
	            for eventcategory in event.event_categories:
		        self.response.out.write(
"""
	        <category>""")
		        if eventcategory.gacategory.categoryparentname:
	                    self.response.out.write(
"""
		    <maincategory>%s</maincategory>
	            <subcategory>%s</subcategory>""" % (eventcategory.gacategory.categoryparentname.key().id() , eventcategory.gacategory.key().id() )
		            )
		        else:
		            self.response.out.write(
"""
	            <maincategory>%s</maincategory>""" %  eventcategory.gacategory.key().id()
		            )
		        self.response.out.write(
"""
	        </category>""")
	        self.response.out.write(
"""
	    </categories>""")
	        eventimages = event.event_images.get()
	        if eventimages != None:
		    mainimage = eventimages.mainimage
		    self.response.out.write(
"""
	<images>"""
		    )
		    if eventimages.mainimage == 1:
                        self.response.out.write(
"""
	    <image main='%s'><img src='/rest/v1/event/img?img_number=1&amp;img_id=%s'></img></image>""" % (mainimage == 1, eventimages.key() )
	      	        )
		    elif eventimages.mainimage == 2:
                        self.response.out.write(
"""
	    <image main='%s'><img src='/rest/v1/event/img?img_number=2&amp;img_id=%s'></img></image>""" % (mainimage == 2, eventimages.key() )
	      	        )
		    elif eventimages.mainimage == 3:
                        self.response.out.write(
"""
	    <image main='%s'><img src='/rest/v1/event/img?img_number=3&amp;img_id=%s'></img></image>""" % (mainimage == 3, eventimages.key() )
	      	        )
		    elif eventimages.mainimage == 4:
                        self.response.out.write(
"""
	    <image main='%s'><img src='/rest/v1/event/img?img_number=4&amp;img_id=%s'></img></image>""" % (mainimage == 4, eventimages.key() )
	      	        )
		    else:
		        self.response.out.write(
"""
	    <image main='%s'><img src='/rest/v1/event/img?img_number=1&amp;img_id=%s'></img></image>""" % (mainimage == 1, eventimages.key() )
	      	        )		
		    self.response.out.write(
"""
	</images>"""
		    )
                if (event.event_locations).count():
                    self.response.out.write(
"""
        <location>"""
		    )
                    for eventlocation in event.event_locations:
	                self.response.out.write(
"""            
	    <id>%d</id>
	    <geocode>%s</geocode>
            <address>%s</address>
            <city>%s</city>
            <state>%s</state>
            <zip>%s</zip>""" % (eventlocation.key().id(), eventlocation.geopoint, eventlocation.address, eventlocation.city, eventlocation.state, eventlocation.zipcode)
		        )
	            self.response.out.write(
"""
	</location>"""
	            )
                if (event.events_users).count():
                    self.response.out.write(
"""
            <attending>"""
                    )
                    for eachuser in event.events_users:
                        self.response.out.write(
"""  
                <user><id>%s</id></user>"""  % eachuser.gauser.key().id() 
	                )
                    self.response.out.write(
"""
            </attending>"""
	            )
                self.response.out.write(
"""
        </event>"""
	        )
            self.response.out.write(
"""
</events>"""
	    )
	    return

	elif version == 'v2':
 	    self.response.headers['Content-Type'] = "application/json"
 	    self.response.headers['Access-Control-Allow-Origin'] = "*"
 	    self.response.headers['Vary'] = "Origin"
 	    self.response.headers['Access-Control-Allow-Methods'] = "OPTIONS, GET, POST, PUT, DELETE"
 	    self.response.headers['Access-Control-Allow-Headers'] = "Content-Type"
 	    eventaccount = {}

	    eventaccount['events']= []
	    #eventaccount['numberofevents'] = events.count() 
	    events = None

	    startdate = self.request.get(u'startdate')
	    if startdate:
	        events = db.GqlQuery(	"SELECT * from Gaevent "+
                                    		"WHERE eventstartdate = :1 " +
						"ORDER BY eventstartdatetime",
                                      		datetime.date(int(startdate[0:4]), int(startdate[4:6]), int(startdate[6:8]) )
	        )
	    daterange = self.request.get(u'daterange') #YYYYMMDDYYYYMMDD
	    if daterange:
	        events = db.GqlQuery(	"SELECT * from Gaevent "+
                                    		"WHERE eventstartdate >= :1 AND eventstartdate <= :2 "+
						"ORDER BY eventstartdate, eventstartdatetime",
                                      		datetime.date(int(daterange[0:4]), int(daterange[4:6]), int(daterange[6:8])),
						datetime.date(int(daterange[8:12]), int(daterange[12:14]), int(daterange[14:16])),
	        )

	    categoryrequest = self.request.get(u'category')
	    if categoryrequest:
	        events = db.GqlQuery(	"SELECT * from Gaevent "+
					"WHERE eventcategories = :1 "+
					"ORDER BY eventstartdatetime",
					int(categoryrequest)
	        )
	    distancerequest = self.request.get(u'distance')
	    if distancerequest: 
		eventaccount['events'] = "does not support distance yet"	
                self.response.out.write( json.dumps(eventaccount) )
	        return		

	    if events == None:
	        events = Gaevent.all()

            for event in events:
		tempevent = {
			     'id': event.key().id(),   
			     'name': event.eventname,
			     'event_start_date': str(event.eventstartdate),
			     'event_start_time': str(event.eventstarttime),
			     'event_expiration': str(event.eventexpiration),
			     'is_featured': event.is_featured,
			     'price': event.price,
			     'likecount': event.likecount,
			     'status': event.is_active,
			     'business': event.gabusiness.key().id(),
			     'date_updated': str(event.date_updated),
			    }

		tempevent['categories'] = []
		tempcategory = {}
		if event.gacategory.categoryparentname:
		    tempcategory['maincategory'] = event.gacategory.categoryparentname.key().id()
		    tempcategory['subcategory'] = event.gacategory.key().id()
		else:
		    tempcategory['maincategory'] = event.gacategory.key().id()
		tempevent['categories'].append(tempcategory)

	        if (event.event_categories).count():  
	            for eventcategory in event.event_categories:
		        tempcategory = {}

		        if eventcategory.gacategory.categoryparentname:
			    tempcategory['maincategory'] = eventcategory.gacategory.categoryparentname.key().id()
			    tempcategory['subcategory'] = eventcategory.gacategory.key().id()
		        else:
			    tempcategory['maincategory'] = eventcategory.gacategory.key().id()
		        tempevent['categories'].append(tempcategory)
	        eventimages = event.event_images.get()
	        if eventimages != None:
		    mainimage = eventimages.mainimage
		    tempevent['images'] = []
		    if eventimages.mainimage == 1:
			tempimage =	{
					'mainimage': mainimage == 1,								
					'imagesrc': "src='/rest/v2/event/img?img_number=1&amp;img_id=%s'" % eventimages.key()
					}
                        tempevent['images'].append(tempimage)
		    elif eventimages.mainimage == 2:
			tempimage =	{
					'mainimage': mainimage == 2,								
					'imagesrc': "src='/rest/v2/event/img?img_number=2&amp;img_id=%s'" % eventimages.key()
					}
                        tempevent['images'].append(tempimage)
		    elif eventimages.mainimage == 3:
			tempimage =	{
					'mainimage': mainimage == 3,								
					'imagesrc': "src='/rest/v2/event/img?img_number=3&amp;img_id=%s'" % eventimages.key()
					}
                        tempevent['images'].append(tempimage)
		    elif eventimages.mainimage == 4:
			tempimage =	{
					'mainimage': mainimage == 4,								
					'imagesrc': "src='/rest/v2/event/img?img_number=4&amp;img_id=%s'" % eventimages.key()
					}
                        tempevent['images'].append(tempimage)
		    else :
			tempimage =	{
					'mainimage': mainimage == 1,								
					'imagesrc': "src='/rest/v2/event/img?img_number=1&amp;img_id=%s'" % eventimages.key()
					}
                        tempevent['images'].append(tempimage)
		tempevent['locations'] = []
	        if (event.event_locations).count():
                    for eventlocation in event.event_locations:
		        temploc = 	{
					'id': eventlocation.key().id(),
					'geocode': str(eventlocation.geopoint),
					'address': eventlocation.address,
					'city': eventlocation.city,
					'state': eventlocation.state,
					'zip': eventlocation.zipcode,
					}
		        tempevent['locations'].append(temploc)

		tempevent['attending'] = []
	        if (event.events_users).count():
                    for eachuser in event.events_users:
		        tempuser =	{
					'id': eachuser.gauser.key().id(),
					}
		        tempevent['attending'].append(tempuser)	
	        eventaccount['events'].append(tempevent)
			
            self.response.out.write( json.dumps(eventaccount) )
	    return

	else:
	    # will have to enter v1 or v2. nothing else should go through
	    return

#full event info
#seems like i have to store businesskey/id in gaevent because can't filter it through gql or query
class EventORSearch(webapp.RequestHandler):
    def options(self):
        self.response.headers['Content-Type'] = "application/json"
        self.response.headers['Access-Control-Allow-Origin'] = "*"
        self.response.headers['Vary'] = "Origin"
        self.response.headers['Access-Control-Allow-Methods'] = "OPTIONS, GET, POST, PUT, DELETE"
        self.response.headers['Access-Control-Allow-Headers'] = "Content-Type"           
        return    
    def get(self):
	# this is a OR result... matching zip or date or category
	
	#all keys for events meeting search criteria are put into list
	eventkeys = []
	categoryrequest = self.request.get(u'category')
	if categoryrequest:
	    cat_info = Gacategory.get_by_id(int(categoryrequest))
	    subcat_info = cat_info.subcategories
	    if subcat_info.count():
		for subcat in subcat_info:
	            subcatevents = subcat.categorys_events
	   	    eventkeys.extend([Gaeventcategory.gaevent.get_value_for_datastore(cat) for cat in subcatevents])		    
	    else:
	        catevents = cat_info.categorys_events
	        eventkeys.extend([Gaeventcategory.gaevent.get_value_for_datastore(cat) for cat in catevents])
	ziprequest = self.request.get(u'zipcode')
	if ziprequest:
	    zipevents = Gaeventlocation.all().filter('zipcode =', ziprequest )
	    eventkeys.extend([Gaeventlocation.gaevent.get_value_for_datastore(loc) for loc in zipevents] )
	startdaterequest = self.request.get(u'startdate')
	if startdaterequest:
	    startdate = startdaterequest
	    dateevents = db.GqlQuery("SELECT __key__ from Gaevent "+
                                     "WHERE eventstartdate = :1",
                                      datetime.date(int(startdate[4:]), int(startdate[:2]), int(startdate[2:4]) ) )
	    eventkeys.extend([each for each in dateevents])
	#after retrieving all the keys, get from the db with matching keys, returns blank if no matching queries
        
	eventkeys = list( set(eventkeys) )
	events = Gaevent.get(eventkeys)

	self.response.headers['Content-Type'] = "text/xml"
        self.response.out.write(
"""<?xml version="1.0" encoding='utf-8'?>
<events>"""
	)
	for event in events:
            self.response.out.write(
"""
        <event>"""
            )
            self.response.out.write(
"""    
	    <id>%s</id>
	    <name>%s</name>
	    <description>%s</description>
	    <tickets>%s</tickets>
	    <supportemail>%s</supportemail>
	    <supportphone>%s</supportphone>
	    <event_start_date>%s</event_start_date>
	    <event_end_date>%s</event_end_date>
	    <event_start_time>%s</event_start_time>
	    <event_end_time>%s</event_end_time>
	    <event_expiration>%s</event_expiration>
	    <is_featured>%s</is_featured>
	    <price>%s</price>
	    <likecount>%s</likecount>
	    <date_created>%s</date_created>
	    <external_id>%s</external_id>
	    <status>%s</status>
	    <business>%s</business>
	    <date_updated>%s</date_updated>""" % (event.key().id(), event.eventname,  event.eventdescription , event.tickets, event.supportemail, event.supportphone, event.eventstartdate, event.eventenddate, event.eventstarttime, event.eventendtime, event.eventexpiration, event.is_featured, event.price, event.likecount, event.date_created, event.external_event_id, event.is_active, event.gabusiness.key().id(), event.date_updated )
	    )
	#all businesses should have one location so these checks might not be needed
	    if (event.event_locations).count():
                self.response.out.write(
"""
            <location>"""
		)
                for eventlocation in event.event_locations:
	            self.response.out.write(
"""
		<id>%d</id>
		<geocode>%s</geocode>
		<address>%s</address>
		<city>%s</city>
		<state>%s</state>
		<zip>%s</zip>""" % (eventlocation.key().id(), eventlocation.geopoint, eventlocation.address, eventlocation.city, eventlocation.state, eventlocation.zipcode)
		    )
	        self.response.out.write(
"""
	    </location>"""
		)
            self.response.out.write(
"""
        </event>"""
	    )
        self.response.out.write(
"""
</events>"""
	)



"""
/rest/(v1|v2)/event/location/id/(uid#)

GET (xml, json)
returns the locations for an event given event id


JSON (v2)
if event has locations
   -returns {'event': {'id':uid, 'locations': [{location} ]} }
if event not valid
   -returns {'event': None}
if event has no locations
   -returns {'event': {'id': uid, 'locations': [] } }

"""

class EventLocation(webapp.RequestHandler):
    def options(self, version, ID):
        self.response.headers['Content-Type'] = "application/json"
        self.response.headers['Access-Control-Allow-Origin'] = "*"
        self.response.headers['Vary'] = "Origin"
        self.response.headers['Access-Control-Allow-Methods'] = "OPTIONS, GET, POST, PUT, DELETE"
        self.response.headers['Access-Control-Allow-Headers'] = "Content-Type"           
        return    
    def get(self, version, ID):
        event= Gaevent.get_by_id(int(ID))
	if version == 'v1':
	    self.response.headers['Content-Type'] = "text/xml"
            self.response.out.write(
"""<?xml version="1.0" encoding='utf-8'?>
<event>"""
	    )
            self.response.out.write(
"""    
	<id>%s</id>""" % event.key().id()
	    )
	    #all businesses should have one location so these checks might not be needed
	    if (event.event_locations).count() :
                self.response.out.write("<location>")
                for eventlocation in event.event_locations:
	            self.response.out.write(
"""
			<id>%d</id>
			<geocode>%s</geocode>
			<address>%s</address>
			<city>%s</city>
			<state>%s</state>
			<zip>%s</zip>""" % (eventlocation.key().id(), eventlocation.geopoint, eventlocation.address, eventlocation.city, eventlocation.state, eventlocation.zipcode)
		    )
	            self.response.out.write("	</location>")
            self.response.out.write(
"""
</event>"""
	    )
	    return

	elif version == 'v2':
 	    self.response.headers['Content-Type'] = "application/json"
 	    self.response.headers['Access-Control-Allow-Origin'] = "*"
 	    self.response.headers['Vary'] = "Origin"
 	    self.response.headers['Access-Control-Allow-Methods'] = "OPTIONS, GET, POST, PUT, DELETE"
 	    self.response.headers['Access-Control-Allow-Headers'] = "Content-Type"
 	    
     	    eventsaccount = {}
	    if event != None:
		tempevent=	{
			'id': event.key().id(),
				}
	        tempevent['locations']= []
	        #all businesses should have one location so these checks might not be needed
	        if (event.event_locations).count() :
                    for eventlocation in event.event_locations:
		        temploc =	{
				'id': eventlocation.key().id(),
				'geocode': str(eventlocation.geopoint),
				'address': eventlocation.address,
				'city': eventlocation.city,
				'state': eventlocation.state, 
				'zip': eventlocation.zipcode,
				  	}
		        tempevent['locations'].append(temploc)

		eventsaccount['event'] = tempevent
                self.response.out.write( json.dumps(eventsaccount) )
	        return

	    else:
		#self.response.out.write( json.dumps(eventsaccount) )
		self.response.out.write( json.dumps({'event': None}) )
		return

	else:
	    # will have to enter v1 or v2. nothing else should go through
	    return

"""
/rest/(v1|v2)/event/categories/zip/(zip#)

GET (xml, json)
returns the categories with events in a given zipcode

JSON(v2)
if zipcode has events
  -returns list of categories that have events in that zipcode {'zipcode':zip#, 'categories':[catid1, catid2,...] }
if zipcode has no evcents
  -returns empty list {'zipcode':zip, 'categories':{} }
"""

#get categories with events in zipcode
class CategoryInfo(webapp.RequestHandler):
    def options(self, version, zipcode):
        self.response.headers['Content-Type'] = "application/json"
        self.response.headers['Access-Control-Allow-Origin'] = "*"
        self.response.headers['Vary'] = "Origin"
        self.response.headers['Access-Control-Allow-Methods'] = "OPTIONS, GET, POST, PUT, DELETE"
        self.response.headers['Access-Control-Allow-Headers'] = "Content-Type"           
        return    
    def get(self, version, zipcode):
        locationsforzip = db.GqlQuery("SELECT * FROM Gaeventlocation " + 
                                      "WHERE zipcode = :1 " +
                         	      "ORDER BY city DESC",
                         	      zipcode)
	if version == 'v1':
	    self.response.headers['Content-Type'] = "text/xml"
            self.response.out.write(
"""<?xml version="1.0" encoding='utf-8'?>
<zip>"""
	    )
            self.response.out.write(
"""    
	<zipcode>%s</zipcode>""" % zipcode
	    )
	    if locationsforzip.count():
                self.response.out.write(
"""
	<categories>""")
	        for location in locationsforzip:
                    for category in location.gaevent.event_categories:
	                self.response.out.write(
"""
			<categoryid>%s</categoryid>""" %  category.gacategory.key().id()
	                )
	        self.response.out.write(
"""
        </categories>"""
	        )
            self.response.out.write(
"""
</zip>"""
	    )
	    return

	elif version == 'v2':
	    self.response.headers['Content-Type'] = "application/json"
	    self.response.headers['Access-Control-Allow-Origin'] = "*"
	    self.response.headers['Vary'] = "Origin"
	    self.response.headers['Access-Control-Allow-Methods'] = "OPTIONS, GET, POST, PUT, DELETE"
	    self.response.headers['Access-Control-Allow-Headers'] = "Content-Type"
            categoryaccount = {}  
	    categoryaccount['categories'] = []

	    categoryaccount['zipcode'] = zipcode
	    if locationsforzip.count():
	        for location in locationsforzip:
                    for category in location.gaevent.event_categories:
			tempcat =  {
				    'categoryid': category.gacategory.key().id()
				    }
	                categoryaccount['categories'].append(tempcat)
            self.response.out.write( json.dumps(categoryaccount) )           
	    return

	else:
	    # will have to enter v1 or v2. nothing else should go through
	    return
	

"""
/rest/(v1|v2)/categories/list

GET (xml,json)
returns all categories that are in database
  -categories come in maincategory, list of subcategories ids 

Json (v2)

{'categories': [{'category': catid, 'date_updated':date, subcategories: [subcatid1, subcatid2, ... ] }, {cat2...}, ... ] }


"""

class CategoryList(webapp.RequestHandler):
    def options(self, version):
        self.response.headers['Content-Type'] = "application/json"
        self.response.headers['Access-Control-Allow-Origin'] = "*"
        self.response.headers['Vary'] = "Origin"
        self.response.headers['Access-Control-Allow-Methods'] = "OPTIONS, GET, POST, PUT, DELETE"
        self.response.headers['Access-Control-Allow-Headers'] = "Content-Type"           
        return    
    def get(self, version):
        categories = Gacategory.all().order('categoryname')
	if version == 'v1':
	    self.response.headers['Content-Type'] = "text/xml"
            self.response.out.write(
"""<?xml version="1.0" encoding='utf-8'?>
<categories>"""
	    )
            for category in categories:
                if category.categoryparentname == None:
		    self.response.out.write(
"""    
        <category>"""
		    )
		    self.response.out.write(
"""
	    <maincategoryid>%s</maincategoryid>
	    <maincategoryname>%s</maincategoryname>
	    <date_updated>%s</date_updated>""" % (category.key().id() , category.categoryname , category.date_updated )
	            )
		    if category.subcategories.count():
			self.response.out.write(
"""
	    <subcategories>"""
			)
                        for each in category.subcategories.order('categoryname'):
		            self.response.out.write(
"""
	        <subcategory>
		    <subcategoryid>%s</subcategoryid>
	    	    <subcategoryname>%s</subcategoryname>
	   	</subcategory>""" % (each.key().id(), each.categoryname)
	                    )
			self.response.out.write(
"""
	    </subcategories>"""
			)
	            self.response.out.write(
"""
        </category>""" 
	            )
	    self.response.out.write(
"""
</categories>""")
	    return

	elif version == 'v2':
	    self.response.headers['Content-Type'] = "application/json"
	    self.response.headers['Content-Type'] = "application/json"
	    self.response.headers['Access-Control-Allow-Origin'] = "*"
	    self.response.headers['Vary'] = "Origin"
	    self.response.headers['Access-Control-Allow-Methods'] = "OPTIONS, GET, POST, PUT, DELETE"
	    self.response.headers['Access-Control-Allow-Headers'] = "Content-Type"
        
	    categoriesaccount = {}
	    categoriesaccount['categories'] = []
            for category in categories:
                if category.categoryparentname == None:
		    tempcat =	{
				'maincategory': category.key().id(),
				'maincategoryname': category.categoryname,
				'date_updated': category.date_updated,
				}
		    tempcat['subcategories'] = []
                    for each in category.subcategories.order('categoryname'):
			tempsubcat = {
					'subcategoryid': each.key().id(),
					'subcategoryname': each.categoryname,
				     }
			tempcat['subcategories'].append (tempsubcat)

		    categoriesaccount['categories'].append(tempcat)

            self.response.out.write( json.dumps(categoriesaccount) )

	else:
	    # will have to enter v1 or v2. nothing else should go through
	    return


#get event location given id
#query string args are in unicode, have to convert
class EventResponse(webapp.RequestHandler):
    def options(self):
        self.response.headers['Content-Type'] = "application/json"
        self.response.headers['Access-Control-Allow-Origin'] = "*"
        self.response.headers['Vary'] = "Origin"
        self.response.headers['Access-Control-Allow-Methods'] = "OPTIONS, GET, POST, PUT, DELETE"
        self.response.headers['Access-Control-Allow-Headers'] = "Content-Type"           
        return    
    def get(self):
        event= Gaevent.get_by_id(7)
	eventimages = event.event_images
	self.response.headers['Content-Type'] = "text/xml"
        self.response.out.write(
"""<?xml version="1.0" encoding='utf-8'?>
<event>"""
	)
        self.response.out.write(
"""
</event>"""
	    )

#Image class page
class EventImagePage (webapp.RequestHandler):
    def options(self, version):
        self.response.headers['Content-Type'] = "application/json"
        self.response.headers['Access-Control-Allow-Origin'] = "*"
        self.response.headers['Vary'] = "Origin"
        self.response.headers['Access-Control-Allow-Methods'] = "OPTIONS, GET, POST, PUT, DELETE"
        self.response.headers['Access-Control-Allow-Headers'] = "Content-Type"           
        return    
    def get(self, version):
        eventimageentity = Gaeventimages.get( self.request.get(u"img_id") )
	imgnumber = self.request.get(u"img_number")
        imagedict = { '1': eventimageentity.image1, '2': eventimageentity.image2, '3':eventimageentity.image3, '4': eventimageentity.image4 }
        if imagedict[imgnumber]:
            self.response.headers['Content-Type'] = "image/png"
            self.response.out.write(imagedict[imgnumber])	
        else:
            self.response.out.write("No image")

class EventImages (webapp.RequestHandler):
    
    def options(self, version, ID):
        self.response.headers['Content-Type'] = "application/json"
        self.response.headers['Access-Control-Allow-Origin'] = "*"
        self.response.headers['Vary'] = "Origin"
        self.response.headers['Access-Control-Allow-Methods'] = "OPTIONS, GET, POST, PUT, DELETE"
        self.response.headers['Access-Control-Allow-Headers'] = "Content-Type"           
        return    
    def get(self, version, ID):

	if version == 'v1':
	    self.response.headers['Content-Type'] = "text/xml"
            self.response.out.write(
"""<?xml version="1.0" encoding='utf-8'?>
<event>"""
	    )
	    event = Gaevent.get_by_id(int(ID))
	    if event != None:
		eventimages = event.event_images.get()
		if eventimages != None:
		    mainimage = eventimages.mainimage
		    self.response.out.write(
"""
	<images>"""
		    )
		    if eventimages.image1:
                        self.response.out.write(
"""
	    <image main='%s'><img src='/rest/v1/event/img?img_number=1&amp;img_id=%s'></img></image>""" % (mainimage == 1, eventimages.key() )
	      	        )
		    if eventimages.image2:
                        self.response.out.write(
"""
	    <image main='%s'><img src='/rest/v1/event/img?img_number=2&amp;img_id=%s'></img></image>""" % (mainimage == 2, eventimages.key() )
	      	        )
		    if eventimages.image3:
                        self.response.out.write(
"""
	    <image main='%s'><img src='/rest/v1/event/img?img_number=3&amp;img_id=%s'></img></image>""" % (mainimage == 3, eventimages.key() )
	      	        )
		    if eventimages.image4:
                        self.response.out.write(
"""
	    <image main='%s'><img src='/rest/v1/event/img?img_number=4&amp;img_id=%s'></img></image>""" % (mainimage == 4, eventimages.key() )
	      	        )
		    self.response.out.write(
"""
	</images>"""
		    )
            self.response.out.write(
"""
</event>"""
	    )
	elif version == 'v2':
	    self.response.headers['Content-Type'] = "application/json"
	    eventaccount = {}
	    eventaccount['eventaccount'] = {}
	    event = Gaevent.get_by_id(int(ID))
	    if event != None:
		eventimages = event.event_images.get()
		if eventimages != None:
		    mainimage = eventimages.mainimage
		    tempevent = {}
		    tempevent['images'] = []
		    if eventimages.image1:
			tempimage = 	{
					'main':mainimage == 1 ,
					'imagesrc':"src='/rest/v2/event/img?img_number=1&amp;img_id=%s'" % eventimages.key()	
					}
                        tempevent['images'].append(tempimage)
		    if eventimages.image2:
			tempimage = 	{
					'main':mainimage == 2,
					'imagesrc':"src='/rest/v2/event/img?img_number=2&amp;img_id=%s'" % eventimages.key()	
					}
                        tempevent['images'].append(tempimage)
		    if eventimages.image3:
			tempimage = 	{
					'main':mainimage == 3,
					'imagesrc':"src='/rest/v2/event/img?img_number=3&amp;img_id=%s'" % eventimages.key()	
					}
                        tempevent['images'].append(tempimage)
		    if eventimages.image4:
			tempimage = 	{
					'main':mainimage == 4,
					'imagesrc':"src='/rest/v2/event/img?img_number=4&amp;img_id=%s'" % eventimages.key()	
					}
                        tempevent['images'].append(tempimage)
                    eventaccount['eventaccount'] = tempevent
                    self.response.out.write( json.dumps( eventaccount ) )
                else:
                    self.response.out.write( json.dumps( {'eventaccount': None} ) )            
            else:
                self.response.out.write( json.dumps( {'eventaccount': None} ) )
        else:
            return

    def post(self, version, ID):
	header = self.request.headers['Content-Type']
	if 'text/xml' in header:
	    self.response.headers['Content-Type'] = "text/xml"
            self.response.out.write(
"""<?xml version="1.0" encoding='utf-8'?>"""
	    )
	    # requiredkeys = set( ['eventaccount', 'id', 'mainimage', 'images', 'image', 'number', 'data' ])
	    imagekeys = set( ['image', 'number', 'data'] )
	    parsed = fromstring(self.request.body)
	    reqeventid = parsed.findtext('id')  
	    event = Gaevent.get_by_id( int(reqeventid) )

	    if event != None:
	        eventimages = event.event_images.get()
	        #this is an update of the user images
	        if eventimages != None:
		    requiredkeys = set( ['eventaccount', ])
		    xmlkeys = set([a.tag for a in parsed.getiterator()] )
	            if requiredkeys.issubset(xmlkeys): 

	            	reqeventid = parsed.findtext('id')
	            	mainnumber = parsed.findtext('mainimage')
	            	reqimages = parsed.find('images')

		    	#this is a required image key check

		    	for each in reqimages or []:
		            eachkeys = set([a.tag for a in each.getiterator()] )
		            if imagekeys.issubset(eachkeys):
			        pass
		            else:
		            	neededkeys = imagekeys - eachkeys
			    	self.response.out.write(
"""
<eventaccount>
    <result>
	<code>%s</code>
	<message>%s</message>
    </result>
</eventaccount>""" % (-1, errors.returnerror['field'] % (neededkeys,'event image'  )  ) #[a for a in neededkeys] all required keys
	        	    	)
			    	return

		        eventimages.mainimage = int(mainnumber or eventimages.mainimage)
	    	        for image in reqimages or []:

				imagenumber = int(image.findtext('number') )
				imagedata_uni= image.findtext('data')
			        imagedata_binary = binascii.a2b_base64(imagedata_uni)

			        if imagenumber == 1:
				    eventimages.image1  = db.Blob(imagedata_binary)
			        elif imagenumber == 2:
				    eventimages.image2  = db.Blob(imagedata_binary)
			        elif imagenumber == 3:
				    eventimages.image3  = db.Blob(imagedata_binary)
			        elif imagenumber == 4:
				    eventimages.image4  = db.Blob(imagedata_binary)
	            	try:
	            	    eventimages.put()
	            	    self.response.out.write(
"""
<eventaccount>
    <result>
	<code>%s</code>
	<message>%s</message>
    </result>
</eventaccount>""" % (0, errors.returnerror['updated'] % ('event image',reqeventid  )  ) #[a for a in neededkeys] all required keys
	            	    )
	            	except:
	            	    self.response.out.write(
"""
<eventaccount>
    <result>
	<code>%s</code>
	<message>%s</message>
    </result>
</eventaccount>""" % (-1, errors.returnerror['transactionfail']  )
	        	    )
			    return
	            else: #not all required keys are there
			neededkeys = requiredkeys - xmlkeys
			self.response.out.write(
"""
<eventaccount>
    <result>
	<code>%s</code>
	<message>%s</message>
    </result>
</eventaccount>""" % (-1, errors.returnerror['field'] % (neededkeys.pop(),'event images'  )  ) #[a for a in neededkeys] all required keys
	        	)
	        #creating new event images
	        else:
		    requiredkeys = set( ['eventaccount', 'mainnumber', 'id', 'images' ])
		    xmlkeys = set([a.tag for a in parsed.getiterator()] )
	            if requiredkeys.issubset(xmlkeys): 

	            	reqeventid = parsed.findtext('id')
	            	mainnumber = parsed.findtext('mainimage')
	            	reqimages = parsed.find('images')
		    	#this is a required image key check

		    	for each in reqimages:
		            eachkeys = set([a.tag for a in each.getiterator()] )
		            if imagekeys.issubset(eachkeys):
			        pass
		            else:
		            	neededkeys = imagekeys - eachkeys
			    	self.response.out.write(
"""
<eventaccount>
    <result>
	<code>%s</code>
	<message>%s</message>
    </result>
</eventaccount>""" % (-1, errors.returnerror['field'] % (neededkeys,'event image'  )  ) #[a for a in neededkeys] all required keys
	        	    	)
			    	return


		        mainnumber = parsed.findtext('mainimage')
		        neweventimages = Gaeventimages(
						parent = event,
						gaevent = event,
		        )
		        neweventimages.mainimage = int(mainnumber)
	    	        for image in reqimages:

				imagenumber = int(image.findtext('number') )
				imagedata_uni= image.findtext('data')
			        imagedata_binary = binascii.a2b_base64(imagedata_uni)

			        if imagenumber == 1:
				    neweventimages.image1  = db.Blob(imagedata_binary)
			        elif imagenumber == 2:
				    neweventimages.image2  = db.Blob(imagedata_binary)
			        elif imagenumber == 3:
				    neweventimages.image3  = db.Blob(imagedata_binary)
			        elif imagenumber == 4:
				    neweventimages.image4  = db.Blob(imagedata_binary)
	    	        try:
	    	            neweventimages.put()
	    	            self.response.out.write(
"""
<eventaccount>
    <result>
	<code>%s</code>
	<message>%s</message>
    </result>
</eventaccount>""" % (0, errors.returnerror['created'] % ('event image',reqeventid  )  ) #[a for a in neededkeys] all required keys
	        	    )
	    	        except:
	    	            self.response.out.write(
"""
<eventaccount>
    <result>
	<code>%s</code>
	<message>%s</message>
    </result>
</eventaccount>""" % (-1, errors.returnerror['transactionfail']  ) #[a for a in neededkeys] all required keys
	    	            )
			    return
	            else: #not all required keys are there
			neededkeys = requiredkeys - xmlkeys
			self.response.out.write(
"""
<eventaccount>
    <result>
	<code>%s</code>
	<message>%s</message>
    </result>
</eventaccount>""" % (-1, errors.returnerror['field'] % (neededkeys.pop(),'event images'  )  ) #[a for a in neededkeys] all required keys
	        	)
	    else:
	        self.response.out.write(
"""
<eventaccount>
    <result>
	<code>%s</code>
	<message>%s</message>
    </result>
</eventaccount>""" % (-2, errors.returnerror['noidfound'] % ('event', reqeventid) )
	        )	    
	    return	


	elif 'application/json' in header:
	    self.response.headers['Content-Type'] = "application/json"
            eventaccount = {}
	    eventaccount['eventaccount'] = {} 
	    reqobj = json.loads(self.request.body)

	    try:
	        reqevent = reqobj['eventaccount']
	    except KeyError, e:
		eventaccount['eventaccount']['result'] = {'code':-1, 'message':(errors.returnerror['accountfield'] % e) }
		self.response.out.write( json.dumps(eventaccount) )
	   	return
	    try:
	        reqeventid = reqevent['id']
		reqimages = reqevent['images']
	    except KeyError, e:
		eventaccount['eventaccount']['result'] = {'code':-1, 'message':errors.returnerror['field'] % (e, 'event images' ) }
		self.response.out.write( json.dumps(eventaccount) )
	    	return

	    event = Gaevent.get_by_id( int(reqeventid) )
	    if event != None:
		addedimage = []
		eventimages = event.event_images.get()
		#this is an update of the user images
		if eventimages != None:
		    mainnumber = optionalargsjson(reqevent, 'mainimage')
		    eventimages.mainimage = int(mainnumber) or eventimages.mainimage
	    	    for image in reqimages:
			#mainimage number, image data, image number
			try:
				imagenumber = int(image['number'])
				imagedata_uni= image['data']
			except KeyError, e:
				eventaccount['eventaccount']['result'] = {'code':-1, 'message':errors.returnerror['field'] % (e, 'event images' ) }
				self.response.out.write( json.dumps(eventaccount) )
	    			return

			imagedata_binary = binascii.a2b_base64(imagedata_uni)
			if imagenumber == 1:
				eventimages.image1  = db.Blob(imagedata_binary)
			elif imagenumber == 2:
				eventimages.image2  = db.Blob(imagedata_binary)
			elif imagenumber == 3:
				eventimages.image3  = db.Blob(imagedata_binary)
			elif imagenumber == 4:
				eventimages.image4  = db.Blob(imagedata_binary)
			try:
		    		eventimages.put()
				addedimage.append(str(imagenumber) + 'passed')
	    	    		eventaccount['eventaccount']['result'] = {'code':0, 'message':errors.returnerror['created'] % ('event image',str(addedimage)  )  } 
			except:
				addedimage.append(str(imagenumber) + 'failed')
	    	    		eventaccount['eventaccount']['result'] = {'code':0, 'message':errors.returnerror['created'] % ('event image',str(addedimage)  )  } 
		    self.response.out.write( json.dumps( eventaccount ) )
		    return
		else:
		    mainnumber = optionalargsjson(reqevent, 'mainimage')
		    neweventimages = Gaeventimages(
						parent = event,
						gaevent = event,
		    )
		    neweventimages.mainimage = mainnumber
	    	    for image in reqimages:
			#mainimage number, image data, image number
			try:
				imagenumber = int(image['number'])
				imagedata_uni= image['data']
			except KeyError, e:
				eventaccount['eventaccount']['result'] = {'code':-1, 'message':errors.returnerror['field'] % (e, 'event images' ) }
				self.response.out.write( json.dumps(eventaccount) )
	    			return

			imagedata_binary = binascii.a2b_base64(imagedata_uni)
			if imagenumber == 1:
				neweventimages.image1  = db.Blob(imagedata_binary)
			elif imagenumber == 2:
				neweventimages.image2  = db.Blob(imagedata_binary)
			elif imagenumber == 3:
				neweventimages.image3  = db.Blob(imagedata_binary)
			elif imagenumber == 4:
				neweventimages.image4  = db.Blob(imagedata_binary)
			try:
		    		neweventimages.put()
				addedimage.append(str(imagenumber) + 'passed')
	    	    		eventaccount['eventaccount']['result'] = {'code':0, 'message':errors.returnerror['updated'] % ('event image',str(addedimage)  )  } 
			except:
				addedimage.append(str(imagenumber) + 'failed')
	    	    		eventaccount['eventaccount']['result'] = {'code':0, 'message':errors.returnerror['updated'] % ('event image',str(addedimage)  )  } 
		self.response.out.write( json.dumps( eventaccount ) )
		return	
	    else:
		eventaccount['eventaccount']['result'] = {'code':-2, 'message':errors.returnerror['noidfound'] % ('event',reqeventid  )  } 
		self.response.out.write( json.dumps( eventaccount ) )
		return

application = webapp.WSGIApplication([
    (r'^/rest/(v1|v2)/event/id/(.*)/?$', EventInfo ),
    (r'^/rest/(v1|v2)/event/lite/id/(.*)/?$', EventLiteInfo ),
    (r'^/rest/(v1|v2)/event/list/?$', EventLiteList),
    (r'^/rest/(v1|v2)/event/filter?$', EventFilter ),
    (r'^/rest/(v1|v2)/event/count?$', EventAmount),
    (r'^/rest/(v1|v2)/event/location/id/(.*)/?$', EventLocation),
    (r'^/rest/(v1|v2)/event/categories/zip/(.*)/?$', CategoryInfo ),
    (r'^/rest/(v1|v2)/categories/list/?$', CategoryList ),
    (r'^/rest/(v1|v2)/event/img', EventImagePage),
    (r'^/rest/(v1|v2)/event/images/id/(.*)/?$', EventImages),
    #(r'^/rest/v1/event/zipcode/(.*)/search?$', EventZipSearch ), #criteria is name value pair?
    #(r'^/rest/v1/event/image?$', EventResponse),
    #(r'^/rest/v1/event/business/id/(.*)/?$', EventforBiz), #this has cat, loc, begindate, enddate, sort, asc/desc
], debug=True)


def main():
    run_wsgi_app(application)


if __name__ == '__main__':
    main()
